package com.lagou.edu;

import com.google.common.collect.Lists;
import com.lagou.edu.decoder.RpcDecoder;
import com.lagou.edu.encoder.RpcEncoder;
import com.lagou.edu.handler.ServerHandler;
import com.lagou.edu.request.RpcRequest;
import com.lagou.edu.response.RpcResponse;
import com.lagou.edu.serializer.JSONSerializer;
import com.lagou.edu.zookeeper.ZookeeperFactory;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.zookeeper.CreateMode;
import org.reflections.Reflections;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

/**
 * @author 赵虎
 * @date 2020/11/25 12:04
 */
@SpringBootApplication
public class ServerBootstrap {

    private static final String SERVICE_PACKAGE = "com.lagou.edu.service";

    private static String ip = "127.0.0.1";

    private static int port;

    private ChannelFuture channelFuture;

    private final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    private final NioEventLoopGroup workGroup = new NioEventLoopGroup();


    public static void main(String[] args) {
        port = Integer.parseInt(args[0]);
        SpringApplication.run(ServerBootstrap.class, args);
    }

    public static List<String> getServiceClass() {
        List<String> serviceList = Lists.newArrayList();
        Reflections reflections = new Reflections(SERVICE_PACKAGE);
        for (Class<?> aClass : reflections.getTypesAnnotatedWith(Service.class)) {
            Class<?>[] interfaces = aClass.getInterfaces();
            if (interfaces.length > 0) {
                for (Class<?> anInterface : interfaces) {
                    serviceList.add(anInterface.getName());
                }
            }
        }
        return serviceList;
    }

    @PostConstruct
    public void startNetty() throws Exception {

        io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                        pipeline.addLast(new ServerHandler());
                    }
                });

        channelFuture = serverBootstrap.bind(port).sync();

        ZookeeperFactory zookeeperFactory = ZookeeperFactory.getInstance(ip, port);
        // 注册zk
        List<String> serviceList = getServiceClass();
        zookeeperFactory.registrationService(serviceList, CreateMode.EPHEMERAL, ip, port);
    }

    @PreDestroy
    public void stopNetty() throws Exception {
        channelFuture.channel().close();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();

        // 清除zk
        ZookeeperFactory zookeeperFactory = ZookeeperFactory.getInstance(ip, port);
        List<String> serviceList = getServiceClass();
        zookeeperFactory.deleteService(serviceList);
    }
}
